package ubi.quando.ServerComm;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import com.google.gson.stream.JsonWriter;

import ubi.quando.App.Contact;
import ubi.quando.App.PickUpParticipant;
import ubi.quando.UI.UbiApplication;

public class ServerWriter {

	private UbiApplication mApp;

	public ServerWriter(UbiApplication mApp) {
		this.mApp = mApp;
	}

	public String writeMeetingInvites(Set<Contact> participants)
			throws IOException {
		Set<String> ids = new HashSet<String>();
		for (Contact contact : participants) {
			ids.add(contact.getId());
		}
		return writeInvites(ids);
	}

	private String writeInvites(Set<String> participants) throws IOException {
		StringWriter sw = new StringWriter();
		JsonWriter writer = new JsonWriter(sw);

		writer.beginArray();
		for (String contact : participants) {
			writer.beginObject();
			writer.name("participantId");
			writer.value(contact);
			writer.endObject();
		}
		writer.endArray();

		return sw.toString();
	}

	public String writePickUpInvites(Collection<PickUpParticipant> participants)
			throws IOException {
		// Set<String> ids = new HashSet<String>();
		// for (PickUpParticipant contact : participants) {
		// ids.add(contact.getContact().getId());
		// }
		// return writeInvites(ids);
		StringWriter sw = new StringWriter();
		JsonWriter writer = new JsonWriter(sw);

		writer.beginArray();
		for (PickUpParticipant contact : participants) {
			writer.beginObject();
			writer.name("participantId");
			writer.value(contact.getContact()/*.getId()*/);
			writer.name("location");
			StringBuilder locationStr = new StringBuilder();
			locationStr.append(contact.getLocation().getLatitudeE6())
					.append(',').append(contact.getLocation().getLongitudeE6());
			writer.value(locationStr.toString());
			writer.name("locName");
			writer.value(contact.getLocName());
			writer.name("time");
			writer.value(contact.getDate().getTime());
			writer.endObject();
		}
		writer.endArray();

		return sw.toString();
	}

}
